package com.useeinfo.oa.modules.security.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Organization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("OrganizationDao")
public class OrganizationDao implements CrudDao<Organization> {
    private final static Logger logger = LoggerFactory.getLogger(OrganizationDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    // ******************************************************************************
    // ******************************* 代码自动生成开始 *******************************
    // ******************************************************************************

    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {

        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String enterpriseId = queryHash.get("enterpriseId");
        if (!StringUtils.isEmpty(enterpriseId)) {
            conditionHash.put("o.enterprise.id = ?{paramIndex}", StringConverters.null2Long(enterpriseId));
        }
        String organizationName = queryHash.get("organizationName");
        if (!StringUtils.isEmpty(organizationName)) {
            conditionHash.put("o.organizationName = ?{paramIndex} ", organizationName);
        }

        String organizationNameLike = queryHash.get("organizationNameLike");
        if (!StringUtils.isEmpty(organizationNameLike)) {
            conditionHash.put("o.organizationName like ?{paramIndex} ", "%" + organizationNameLike + "%");
        }

        String lvl = queryHash.get("lvl");
        if (!StringUtils.isEmpty(lvl)) {
            conditionHash.put("lvl = ?{paramIndex} ", StringConverters.ToInteger(lvl));
        }

        String beginLft = queryHash.get("beginLft");
        if (!StringUtils.isEmpty(beginLft)) {
            conditionHash.put("lft >= ?{paramIndex} ", StringConverters.ToInteger(beginLft));
        }

        String endRgt = queryHash.get("endRgt");
        if (!StringUtils.isEmpty(endRgt)) {
            conditionHash.put("rgt <= ?{paramIndex} ", StringConverters.ToInteger(endRgt));
        }

        String organizationId = queryHash.get("organizationId");
        if (!StringUtils.isEmpty(organizationId)) {
            conditionHash.put("id = ?{paramIndex} ", StringConverters.ToLong(organizationId));
        }
        String parentId = queryHash.get("parentId");
        if (!StringUtils.isEmpty(parentId)) {
            conditionHash.put("parentId = ?{paramIndex} ", StringConverters.ToLong(parentId));
        }

        String addparentId = queryHash.get("addparentId");
        if (!StringUtils.isEmpty(addparentId) && "-1".equals(addparentId)) {
            conditionHash.put("o.parentId IS NULL ", null);
        } else  if (!StringUtils.isEmpty(addparentId) && !"-1".equals(addparentId)) {
            conditionHash.put("o.parentId = ?{paramIndex} ", StringConverters.ToLong(addparentId));
        }

        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(o) from Organization o ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<Organization> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select o from Organization o ", "order by o.id desc ");

        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Organization> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Organization.class);

        return queryParam.findPageList(typedQuery);
    }

    @Override
    public Organization findModel(Long id) {
        return entityManager.find(Organization.class, id);
    }

    @Override
    public Integer add(Organization model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("OrganizationImpl添加Organization成功！");
        return 1;
    }

    @Override
    public Integer update(Organization model) {
        return null;
    }

    @Override
    public Integer delete(Long id) {
        return null;
    }

    @Override
    public Integer deleteLogic(Organization model) {
        return null;
    }


    //根据id查询结构
    public List getChildOrganizationById(Long parent_id) {
        String sql = "SELECT id,organization_name,lvl,parent_id FROM organization WHERE  delete_status= false and parent_id=" + parent_id + " ORDER BY lvl ASC";
        return entityManager.createNativeQuery(sql).getResultList();
    }

    /**
     * @param num
     * @return
     */
    public synchronized Integer updateOrganizationRgt(Integer num) {
        String sql = "UPDATE organization SET rgt=rgt+2 WHERE rgt>" + num;
        Query query = entityManager.createNativeQuery(sql);
        try {
            return query.executeUpdate();
        } catch (Exception ex) {
            return 0;
        }
    }

    /**
     * @param num
     * @return
     */
    public synchronized Integer updateOrganizationLft(Integer num) {
        String sql = "UPDATE organization SET lft=lft+2 WHERE lft>" + num;
        Query query = entityManager.createNativeQuery(sql);
        try {
            return query.executeUpdate();
        } catch (Exception ex) {
            return 0;
        }
    }


    public List<Organization> hqlExcute(String hql) {
        return entityManager.createQuery(hql,Organization.class).getResultList();
    }

}
